#!/bin/bash

# 重新编译、打包和安装脚本

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

PASSWORD="${1:-openeuler@123}"

echo "=========================================="
echo "重新编译、打包和安装网络管理器GUI"
echo "=========================================="
echo ""

# 步骤1: 清理
echo "步骤1: 清理旧文件..."
make clean 2>/dev/null || true
rm -f *.rpm
echo "✓ 清理完成"
echo ""

# 步骤2: 重新生成Makefile
echo "步骤2: 重新生成Makefile..."
/usr/lib64/qt5/bin/qmake network_manager_gui.pro
echo "✓ Makefile生成完成"
echo ""

# 步骤3: 编译
echo "步骤3: 编译项目..."
make -j$(nproc)
if [ ! -f network_manager_gui ]; then
    echo "✗ 编译失败！"
    exit 1
fi
echo "✓ 编译完成"
echo ""

# 步骤4: 卸载旧包
echo "步骤4: 卸载旧安装包..."
if rpm -q network-manager-gui >/dev/null 2>&1; then
    echo "发现已安装的包，正在卸载..."
    echo "$PASSWORD" | sudo -S rpm -e network-manager-gui || true
    echo "✓ 卸载完成"
else
    echo "未发现已安装的包"
fi
echo ""

# 步骤5: 打包RPM
echo "步骤5: 打包RPM..."
bash ./build_rpm.sh
RPM_FILE=$(ls -t *.rpm 2>/dev/null | head -1)
if [ -z "$RPM_FILE" ] || [ ! -f "$RPM_FILE" ]; then
    echo "✗ RPM打包失败！"
    exit 1
fi
echo "✓ RPM打包完成: $RPM_FILE"
echo ""

# 步骤6: 安装新包
echo "步骤6: 安装新RPM包..."
echo "$PASSWORD" | sudo -S rpm -ivh "$RPM_FILE"
echo "✓ 安装完成"
echo ""

# 步骤7: 验证
echo "步骤7: 验证安装..."
if [ -f /opt/netmanager/network_manager_gui ]; then
    echo "✓ 可执行文件存在"
    
    # 检查依赖
    MISSING_LIBS=$(ldd /opt/netmanager/network_manager_gui 2>&1 | grep -i "not found" || true)
    if [ -n "$MISSING_LIBS" ]; then
        echo "⚠ 警告: 发现缺失的依赖库"
        echo "$MISSING_LIBS"
    else
        echo "✓ 所有依赖库正常"
    fi
    
    # 检查Qt插件
    if [ -f /opt/netmanager/lib/qt5/plugins/platforms/libqxcb.so ]; then
        echo "✓ Qt平台插件存在"
    else
        echo "⚠ 警告: Qt平台插件缺失"
    fi
else
    echo "✗ 安装验证失败"
    exit 1
fi

echo ""
echo "=========================================="
echo "完成！现在可以运行程序:"
echo "  /opt/netmanager/run.sh"
echo "=========================================="

